#!/bin/bash

echo "=================================================="
echo "         AutoRun 自动化脚本管理平台 停止脚本"
echo "=================================================="

# 解析停止选项
BACKEND_ONLY=false
FRONTEND_ONLY=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --backend-only)
            BACKEND_ONLY=true
            shift
            ;;
        --frontend-only)
            FRONTEND_ONLY=true
            shift
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  --backend-only   只停止后端服务"
            echo "  --frontend-only  只停止前端服务"
            echo "  --help           显示帮助信息"
            echo ""
            echo "默认停止所有服务"
            exit 0
            ;;
        *)
            echo "未知选项: $1"
            echo "使用 --help 查看帮助信息"
            exit 1
            ;;
    esac
done

# 停止后端服务
stop_backend() {
    echo "🛑 停止后端服务..."
    
    # 查找Java autorun进程
    JAVA_PIDS=$(ps -ef | grep "java.*autorun-server" | grep -v grep | awk '{print $2}')
    if [ ! -z "$JAVA_PIDS" ]; then
        echo "   找到Java进程: $JAVA_PIDS"
        for pid in $JAVA_PIDS; do
            echo "   停止进程 $pid"
            kill -9 $pid 2>/dev/null || true
        done
    else
        echo "   未找到Java autorun进程"
    fi
    
    # 查找占用8891端口的进程
    PORT_PIDS=$(ps -ef | grep ":8891" | grep -v grep | awk '{print $2}')
    if [ ! -z "$PORT_PIDS" ]; then
        echo "   找到8891端口进程: $PORT_PIDS"
        for pid in $PORT_PIDS; do
            echo "   停止进程 $pid"
            kill -9 $pid 2>/dev/null || true
        done
    fi
    
    echo "✅ 后端服务已停止"
}

# 停止前端服务
stop_frontend() {
    echo "🛑 停止前端服务..."
    
    # 查找npm run dev进程
    NPM_PIDS=$(ps -ef | grep "npm run dev" | grep -v grep | awk '{print $2}')
    if [ ! -z "$NPM_PIDS" ]; then
        echo "   找到npm进程: $NPM_PIDS"
        for pid in $NPM_PIDS; do
            echo "   停止进程 $pid"
            kill -9 $pid 2>/dev/null || true
        done
    else
        echo "   未找到npm run dev进程"
    fi
    
    # 查找vue-cli-service进程
    VUE_PIDS=$(ps -ef | grep "vue-cli-service" | grep -v grep | awk '{print $2}')
    if [ ! -z "$VUE_PIDS" ]; then
        echo "   找到vue-cli-service进程: $VUE_PIDS"
        for pid in $VUE_PIDS; do
            echo "   停止进程 $pid"
            kill -9 $pid 2>/dev/null || true
        done
    fi
    
    # 查找占用8081端口的进程
    PORT_PIDS=$(ps -ef | grep ":8081" | grep -v grep | awk '{print $2}')
    if [ ! -z "$PORT_PIDS" ]; then
        echo "   找到8081端口进程: $PORT_PIDS"
        for pid in $PORT_PIDS; do
            echo "   停止进程 $pid"
            kill -9 $pid 2>/dev/null || true
        done
    fi
    
    echo "✅ 前端服务已停止"
}

# 主流程
if [ "$FRONTEND_ONLY" = true ]; then
    stop_frontend
    echo ""
    echo "🎉 前端服务已停止！"
    
elif [ "$BACKEND_ONLY" = true ]; then
    stop_backend
    echo ""
    echo "🎉 后端服务已停止！"
    
else
    # 停止所有服务
    stop_backend
    stop_frontend
    echo ""
    echo "🎉 所有服务已停止！"
fi